#pragma once

#include "api/media_stream_interface.h"
#include "api/scoped_refptr.h"

namespace p2pms {

// 专门用于代理视频轨道的适配器
class VideoTrackProxy : public webrtc::VideoTrackInterface,
						public rtc::RefCountedObject<VideoTrackProxy> 
{
public:
	explicit VideoTrackProxy(webrtc::VideoTrackInterface* target_track)
		: target_track_(target_track) {
		RTC_DCHECK(target_track_);
	}

	// --- 实现 MediaStreamTrackInterface 的方法 ---
	std::string kind() const override { return target_track_->kind(); }
	std::string id() const override { return target_track_->id(); }
	TrackState state() const override { return target_track_->state(); }
	bool enabled() const override { return target_track_->enabled(); }
	bool set_enabled(bool enable) override { return target_track_->set_enabled(enable); }
	void RegisterObserver(webrtc::ObserverInterface* observer) override { target_track_->RegisterObserver(observer); }
	void UnregisterObserver(webrtc::ObserverInterface* observer) override { target_track_->UnregisterObserver(observer); }

	// --- 实现 VideoTrackInterface 特有的方法 ---
	void AddOrUpdateSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink,
						 const rtc::VideoSinkWants& wants) override {
		target_track_->AddOrUpdateSink(sink, wants);
	}

	void RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) override {
		target_track_->RemoveSink(sink);
	}

	webrtc::VideoTrackSourceInterface* GetSource() const override {
		return target_track_->GetSource();
	}

protected:
	~VideoTrackProxy() override = default;

private:
	webrtc::VideoTrackInterface* const target_track_;
};

// 工厂函数，根据裸指针的类型创建并返回一个安全的、可被引用计数的代理
inline rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>
CreateTrackProxy(webrtc::MediaStreamTrackInterface* raw_track) {
	if (!raw_track) {
		return nullptr;
	}

	if (raw_track->kind() == webrtc::MediaStreamTrackInterface::kVideoKind) {
		auto* video_track = static_cast<webrtc::VideoTrackInterface*>(raw_track);
		// 创建 VideoTrackProxy 并返回一个指向基类的智能指针
		return new rtc::RefCountedObject<VideoTrackProxy>(video_track);
	}
	
	if (raw_track->kind() == webrtc::MediaStreamTrackInterface::kAudioKind) {
		// auto* audio_track = static_cast<webrtc::AudioTrackInterface*>(raw_track);
		// return new rtc::RefCountedObject<AudioTrackProxy>(audio_track);
		// 暂不处理音频
		return nullptr;
	}

	return nullptr;
}


} // namespace p2pms